package com.tanhua.sso.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.vo.PicUploadResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @program: my-tanhua
 * @description:
 * @author: xuejingjing
 * @create: 2021-09-20 13:17
 **/

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    //人脸识别的校验
    @Autowired
    private FaceEngineService faceEngineService;

    //图片上传
    @Autowired
    private PicUploadService picUploadService;


    public Boolean saveUserInfo(Map<String, String> param, String token) {

        //校验token
       User user =  userService.queryUserByToken(token);
       //如果这个user有值，说明直接登录就行了；如果没值，说明，这是个新用户。
        if(null == user){
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"),"man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        return  userInfoMapper.insert(userInfo) == 1;

    }

    /**
     * 上传照片
     * @param multipartFile
     * @param token
     * @return
     */
    public Boolean saveUserLogo(MultipartFile multipartFile, String token) {
        //校验token
        User user =  userService.queryUserByToken(token);
        //如果这个user有值，说明直接登录就行了；如果没值，说明，这是个新用户。
        if(null == user){
            return false;
        }
        //校验图片是否是人像，如果不是人像就返回false
        try {
            boolean b = faceEngineService.checkIsPortrait(multipartFile.getBytes());
            if(!b){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //是人像，就需要把图片上传到阿里云的oss
        PicUploadResult result = picUploadService.upload(multipartFile);
        if(StringUtils.isEmpty(result.getName())){
            //上传失败
            return false;
        }
        //把头像保存到用户信息表中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        //UserInfo的id 和User的id为啥是同一个？？？？？？？？
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",user.getId());
        //根据id更新这个用户
        return userInfoMapper.update(userInfo,queryWrapper) ==1;




    }
}